from django import forms
from django.forms import inlineformset_factory
from django.shortcuts import render, redirect, get_object_or_404
from django.core.paginator import Paginator
from django.urls import reverse
from django.http import HttpResponseRedirect
from myadmin.models import Recipes, RecipeIngredients, Foods


def index(request, pIndex=1):
    """浏览食谱列表"""
    # 获取搜索关键词
    search_keyword = request.GET.get('search', '').strip()
    
    # 基础查询集
    recipe_list = Recipes.objects.all()
    
    # 如果有搜索关键词，添加过滤条件
    if search_keyword:
        recipe_list = recipe_list.filter(
            recipe_name__icontains=search_keyword  # 搜索食谱名称
        ) | recipe_list.filter(
            description__icontains=search_keyword  # 搜索描述
        )
    
    # 按创建时间倒序
    recipe_list = recipe_list.order_by('-created_at')
    
    # 分页处理
    p = Paginator(recipe_list, 5)  # 每页5条数据
    if pIndex < 1:
        pIndex = 1
    if pIndex > p.num_pages:
        pIndex = p.num_pages
    recipe_list = p.page(pIndex)
    
    # 上下文包含所有食谱数据和搜索关键词
    context = {
        'recipe_list': recipe_list,
        'pIndex': pIndex,
        'total_pages': p.num_pages,
        'search_keyword': search_keyword  # 传递搜索关键词用于回显
    }
    return render(request, 'myadmin/recipes/index.html', context)


def add(request):
    """加载添加食谱表单"""
    foods = Foods.objects.all().order_by('food_name')
    context = {
        'foods': foods
    }
    return render(request, 'myadmin/recipes/add.html', context)


def insert(request):
    """执行添加食谱"""
    try:
        # 获取表单数据
        recipe_name = request.POST.get('recipe_name').strip()
        description = request.POST.get('description', '').strip()
        prep_time = request.POST.get('prep_time')
        cook_time = request.POST.get('cook_time')
        total_calories = request.POST.get('total_calories')
        is_suitable_for_chronic = request.POST.get('is_suitable_for_chronic', '0') == '1'
        
        # 验证数据
        if not recipe_name:
            context = {'info': '食谱名称不能为空！'}
            return render(request, 'myadmin/info.html', context)
        
        # 检查食谱名称是否已存在
        if Recipes.objects.filter(recipe_name=recipe_name).exists():
            context = {'info': '该食谱名称已存在！'}
            return render(request, 'myadmin/info.html', context)
        
        # 创建食谱
        recipe = Recipes()
        recipe.recipe_name = recipe_name
        recipe.description = description
        recipe.prep_time = int(prep_time) if prep_time and prep_time.isdigit() else None
        recipe.cook_time = int(cook_time) if cook_time and cook_time.isdigit() else None
        recipe.total_calories = float(total_calories) if total_calories else None
        recipe.is_suitable_for_chronic = is_suitable_for_chronic
        recipe.save()
        
        context = {'info': '添加食谱成功！'}
    except Exception as e:
        context = {'info': f'添加食谱失败：{str(e)}'}
    return render(request, 'myadmin/info.html', context)


def detail(request, recipe_id):
    """查看食谱详情（包含食材列表）"""
    recipe = get_object_or_404(Recipes, recipe_id=recipe_id)
    ingredients = RecipeIngredients.objects.filter(recipe=recipe).select_related('food')
    context = {
        'recipe': recipe,
        'ingredients': ingredients
    }
    return render(request, 'myadmin/recipes/detail.html', context)


def edit(request, recipe_id):
    """加载编辑食谱表单"""
    recipe = get_object_or_404(Recipes, recipe_id=recipe_id)
    # 创建食材表单集
    RecipeIngredientFormSet = inlineformset_factory(
        Recipes, RecipeIngredients,
        fields=['food', 'quantity', 'unit'],
        extra=0  # 不显示额外空表单
    )
    
    if request.method == 'POST':
        # 处理表单提交
        # 这里可以根据实际需求添加表单验证和保存逻辑
        recipe.recipe_name = request.POST.get('recipe_name').strip()
        recipe.description = request.POST.get('description', '').strip()
        recipe.prep_time = request.POST.get('prep_time')
        recipe.cook_time = request.POST.get('cook_time')
        recipe.total_calories = request.POST.get('total_calories')
        recipe.is_suitable_for_chronic = request.POST.get('is_suitable_for_chronic', '0') == '1'
        
        # 保存食谱基本信息
        recipe.save()
        
        # 处理食材表单集
        formset = RecipeIngredientFormSet(request.POST, instance=recipe)
        if formset.is_valid():
            formset.save()
            return redirect('myadmin_recipes_index')
    else:
        # 初始加载表单
        formset = RecipeIngredientFormSet(instance=recipe)
    
    foods = Foods.objects.all().order_by('food_name')
    context = {
        'recipe': recipe,
        'formset': formset,
        'foods': foods
    }
    return render(request, 'myadmin/recipes/edit.html', context)


def update(request, recipe_id):
    """执行编辑食谱"""
    try:
        recipe = get_object_or_404(Recipes, recipe_id=recipe_id)
        
        # 获取表单数据
        recipe_name = request.POST.get('recipe_name').strip()
        description = request.POST.get('description', '').strip()
        prep_time = request.POST.get('prep_time')
        cook_time = request.POST.get('cook_time')
        total_calories = request.POST.get('total_calories')
        is_suitable_for_chronic = request.POST.get('is_suitable_for_chronic', '0') == '1'
        
        # 验证核心数据
        if not recipe_name:
            context = {'info': '食谱名称不能为空！'}
            return render(request, 'myadmin/info.html', context)
        
        # 检查食谱名称是否已存在（排除当前食谱）
        if Recipes.objects.filter(recipe_name=recipe_name).exclude(recipe_id=recipe_id).exists():
            context = {'info': '该食谱名称已存在！'}
            return render(request, 'myadmin/info.html', context)
        
        # 更新字段
        recipe.recipe_name = recipe_name
        recipe.description = description
        recipe.prep_time = int(prep_time) if prep_time and prep_time.isdigit() else None
        recipe.cook_time = int(cook_time) if cook_time and cook_time.isdigit() else None
        recipe.total_calories = float(total_calories) if total_calories else None
        recipe.is_suitable_for_chronic = is_suitable_for_chronic
        recipe.save()
        
        context = {'info': '更新食谱成功！'}
    except Exception as e:
        context = {'info': f'更新食谱失败：{str(e)}'}
    return render(request, 'myadmin/info.html', context)


def delete(request, recipe_id):
    """删除食谱"""
    try:
        recipe = get_object_or_404(Recipes, recipe_id=recipe_id)
        recipe.delete()
        return HttpResponseRedirect(reverse('myadmin_recipes_index', args=[1]))
    except Exception as e:
        context = {'info': f'删除食谱失败：{str(e)}'}
        return render(request, 'myadmin/info.html', context)


# 食谱成分相关操作
def ingredient_add(request, recipe_id):
    """添加食谱成分"""
    recipe = get_object_or_404(Recipes, recipe_id=recipe_id)
    foods = Foods.objects.all().order_by('food_name')
    context = {
        'recipe': recipe,
        'foods': foods
    }
    return render(request, 'myadmin/recipes/ingredient_add.html', context)


def ingredient_insert(request, recipe_id):
    """执行添加食谱成分"""
    try:
        recipe = get_object_or_404(Recipes, recipe_id=recipe_id)
        
        food_id = request.POST.get('food_id')
        quantity = request.POST.get('quantity')
        unit = request.POST.get('unit', 'g').strip()
        
        if not all([food_id, quantity]):
            context = {'info': '食物和数量不能为空！'}
            return render(request, 'myadmin/info.html', context)
        
        ingredient = RecipeIngredients()
        ingredient.recipe = recipe
        ingredient.food = get_object_or_404(Foods, food_id=food_id)
        ingredient.quantity = float(quantity)
        ingredient.unit = unit
        ingredient.save()
        
        return HttpResponseRedirect(reverse('myadmin_recipes_detail', args=[recipe_id]))
    except Exception as e:
        context = {'info': f'添加食材失败：{str(e)}'}
        return render(request, 'myadmin/info.html', context)


def ingredient_edit(request, ingredient_id):
    """编辑食谱成分"""
    ingredient = get_object_or_404(RecipeIngredients, id=ingredient_id)
    foods = Foods.objects.all().order_by('food_name')
    context = {
        'ingredient': ingredient,
        'foods': foods
    }
    return render(request, 'myadmin/recipes/ingredient_edit.html', context)


def ingredient_update(request, ingredient_id):
    """执行更新食谱成分"""
    try:
        ingredient = get_object_or_404(RecipeIngredients, id=ingredient_id)
        
        food_id = request.POST.get('food_id')
        quantity = request.POST.get('quantity')
        unit = request.POST.get('unit', 'g').strip()
        
        if not all([food_id, quantity]):
            context = {'info': '食物和数量不能为空！'}
            return render(request, 'myadmin/info.html', context)
        
        ingredient.food = get_object_or_404(Foods, food_id=food_id)
        ingredient.quantity = float(quantity)
        ingredient.unit = unit
        ingredient.save()
        
        return HttpResponseRedirect(reverse('myadmin_recipes_detail', args=[ingredient.recipe.recipe_id]))
    except Exception as e:
        context = {'info': f'更新食材失败：{str(e)}'}
        return render(request, 'myadmin/info.html', context)


def ingredient_delete(request, ingredient_id):
    """删除食谱成分"""
    try:
        ingredient = get_object_or_404(RecipeIngredients, id=ingredient_id)
        recipe_id = ingredient.recipe.recipe_id
        ingredient.delete()
        return HttpResponseRedirect(reverse('myadmin_recipes_detail', args=[recipe_id]))
    except Exception as e:
        context = {'info': f'删除食材失败：{str(e)}'}
        return render(request, 'myadmin/info.html', context)